package context

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"ywebgo/utils"
)

type Context struct {
	W http.ResponseWriter
	R *http.Request
}

func (c *Context) ReadJson(data interface{}) {
	bytes, err := io.ReadAll(c.R.Body)
	if err != nil {
		fmt.Fprintf(c.W, "read body faild: %v", err)
	}

	err = json.Unmarshal(bytes, data)
	if err != nil {
		fmt.Fprintf(c.W, "deserialized failed: %v", err)
		return
	}
}

func (c *Context) ResultNone() {
	c.ResultOK(nil)
}
func (c *Context) ResultOK(data interface{}) {
	c.ResultOKMsg("", data)
}

func (c *Context) ResultOKMsg(msg string, data interface{}) {
	result := utils.ResultOKMsg(msg, data)
	bytes, err := json.Marshal(result)
	if err != nil {
		fmt.Fprintf(c.W, "serialized failed: %v", err)
		return
	}

	fmt.Fprintf(c.W, string(bytes))
}

func NewContext(w http.ResponseWriter, r *http.Request) *Context {
	return &Context{W: w, R: r}
}
